//-----------------------------------------------------------------------
// <copyright file="Create.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Mark Phillips</author>
// <email>andyr</email>
// <date>2004-03-23</date>
// <summary>Creates a new FtpSite.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Sdc.Tasks.Web.FtpSite
{
    using System;
    using System.Globalization;
    using Microsoft.Sdc.Tasks.Configuration.Web;
    using Microsoft.Build.Framework;

    /// <summary>
    /// Create a new FTP site.
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[<Web.FtpSite.Create
    ///     Description="description"
    ///     Path="path" 
    ///     IPAddress="ipAddress"
    ///     Port="port"
    ///     AccessFlags="accessflags" 
    ///     AllowAnonymous="allowAnonymous"
    ///     AnonymousUsername="anonymousUsername"
    ///     AnonymousPassword="anonymousPassword"
    ///     Identifier="identifier"
    ///     HostName="hostName"  />]]></code>
    /// <para>where:</para>
    /// <para><i>description (Required)</i></para>
    /// <para>A description for the FTP site to be created.</para>
    /// <para><i>path (Required)</i></para>
    /// <para>Local path to assign as the FTP root.</para>
    /// <para><i>ipAddress</i></para>
    /// <para>IP address to listen on. This can be any valid IPV4 address. 
    /// If this IP address is not bound to a local NIC the FTP server will not start.
    /// If this property is not set, the FTP site will listen on all available 
    /// addresses on the hosting machine.</para>
    /// <para><i>port</i></para>
    /// <para>Port for the FTP site to listen on.</para>
    /// <para><i>allowAnonymous</i></para>
    /// <para>Set to true to allow access to anonymous users</para>
    /// <para><i>anonymousUsername</i></para>
    /// <para>Account to run anonymous users under</para>
    /// <para><i>anonymousPassword</i></para>
    /// <para>Password for the anonymous users account</para>
    /// <para><i>accessFlags</i></para>
    /// <para>Access flags for the FTP site (either "AccessRead", "AccessWrite", or both combined)</para>
    /// <para><i>identifier</i></para>
    /// <para>Any non-existant FTP site identifier.</para>
    /// <para><i>hostName</i></para>
    /// <para>Host header to bind to (only valid for non-SSL sites).</para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///         <Web.FtpSite.Create
    ///             Description="TestFTP"
    ///             Path="c:\inetpub\testftp"
    ///             AllowAnonymous="false"
    ///             AccessFlags="AccessRead"
    ///            />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>    
    public class Create : TaskBase
    {
        private string description;
        private string path;
        private string ipAddress;
        private string port;
        private string hostName;
        private string identifier;
        private string accessFlagsFromConfig;
        private bool allowAnonymous = true;
        private string anonymousUserName;
        private string anonymousUserPass;
        private AccessFlags accessFlags = 0;
        private Microsoft.Sdc.Tasks.Configuration.Web.FtpSite ftp;
        private string userIsolationMode;

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            #region Execute code

            if (accessFlagsFromConfig == null || accessFlagsFromConfig.Length == 0)
            {
                accessFlags = Microsoft.Sdc.Tasks.Configuration.Web.AccessFlags.AccessNoAccess;
            }
            else
            {
                string[] accessFlagsSplit = accessFlagsFromConfig.Split(' ');
                foreach (string accessFlagsSplitItem in accessFlagsSplit)
                {
                    object flags = Enum.Parse(typeof (AccessFlags), accessFlagsSplitItem, true);
                    accessFlags = accessFlags | (AccessFlags) flags;
                }
            }

            if (Microsoft.Sdc.Tasks.Configuration.Web.FtpSite.Exists(description))
            {
                Log.LogMessageFromResources(MessageImportance.Low, "Web.WebSiteExists", description);
            }
            else
            {
                if (path == null || path.Length == 0)
                {
                    throw new TaskException("Web.PathNotSpecified");
                }
                if (description == null || description.Length == 0)
                {
                    throw new TaskException("Web.DescriptionNotSpecified");
                }
                Log.LogMessageFromResources("Web.CreateFtpSite", description);

                if (port == null || port.Length == 0)
                {
                    port = "21";
                }

                if (userIsolationMode == null || userIsolationMode.Length == 0)
                {
                    userIsolationMode = "0";
                }

                ftp = new Microsoft.Sdc.Tasks.Configuration.Web.FtpSite();
                ftp.Description = description;
                ftp.Path = System.IO.Path.GetFullPath(path);
                ftp.Port = Convert.ToInt32(port, CultureInfo.InvariantCulture);
                ftp.RootAccessFlags = accessFlags;
                ftp.AllowAnonymous = allowAnonymous;
                ftp.UserIsolationMode = Convert.ToInt32(this.userIsolationMode, CultureInfo.InvariantCulture);

                if (anonymousUserName != null && anonymousUserName.Length > 0)
                {
                    ftp.AnonymousUserName = anonymousUserName;
                }

                if (anonymousUserPass != null && anonymousUserPass.Length > 0)
                {
                    ftp.AnonymousUserPass = anonymousUserPass;
                }

                if (ipAddress != null && ipAddress.Length > 0)
                {
                    ftp.IPAddress = System.Net.IPAddress.Parse(ipAddress);
                }
                if (identifier != null && identifier.Length > 0)
                {
                    ftp.Identifier = Convert.ToInt32(identifier, CultureInfo.InvariantCulture);
                }
                if (hostName != null && hostName.Length > 0)
                {
                    ftp.HostName = hostName;
                }
                ftp.Save();
            }

            #endregion
        }


        /// <summary>
        /// FTP site description
        /// </summary>
        /// <value>Any valid description for the FTP site</value>
        [Required]
        public string Description
        {
            get { return (description == null ? String.Empty : description); }
            set { description = value; }
        }

        /// <summary>
        /// Root path for the ftp site
        /// </summary>
        /// <value>Existing directory path</value>
        [Required]
        public string Path
        {
            get { return (path == null ? String.Empty : path); }
            set { path = value; }
        }

        /// <summary>
        /// IP address to listen on
        /// </summary>
        /// <value>Any valid IPV4 address. 
        /// If this IP address is not bound to a local
        /// NIC the FTP server will not start.
        /// If this property is not set the ftp site will listen on all available 
        /// addresses on the hosting machine</value>
        public string IPAddress
        {
            get { return (ipAddress == null ? String.Empty : ipAddress); }
            set { ipAddress = value; }
        }

        /// <summary>
        /// Port for the FTP site to listen on
        /// </summary>
        /// <value>A valid port number.</value>
        public string Port
        {
            get { return (port == null ? String.Empty : port); }
            set { port = value; }
        }


        /// <summary>
        /// FTP site identifier
        /// </summary>
        /// <value>Any non-existant ftp site identifier</value>
        public string Identifier
        {
            get { return (identifier == null ? String.Empty : identifier); }
            set { identifier = value; }
        }

        /// <summary>
        /// Access flags for the FTP site
        /// </summary>
        /// <value>Can be:
        /// "AccessRead"
        /// "AccessWrite"
        /// These two values may be combined.</value>
        public string AccessFlags
        {
            get { return (accessFlagsFromConfig == null ? String.Empty : accessFlagsFromConfig); }
            set { accessFlagsFromConfig = value; }
        }

        /// <summary>
        /// Allow anonymous access to the FTP site
        /// </summary>
        /// <value>True to allow anonymous access to the FTP site, otherwise false</value>
        public bool AllowAnonymous
        {
            get { return allowAnonymous; }
            set { allowAnonymous = value; }
        }

        /// <summary>
        /// Username context to run any anonymous connections under
        /// </summary>
        /// <value>A valid NT account</value>
        public string AnonymousUserName
        {
            get { return (anonymousUserName == null ? String.Empty : anonymousUserName); }
            set { anonymousUserName = value; }
        }

        /// <summary>
        /// Password for the <see cref="AnonymousUserName">anonymous user name</see>
        /// </summary>
        /// <value>A valid password for the anonymous account</value>
        public string AnonymousUserPass
        {
            get { return (anonymousUserPass == null ? String.Empty : anonymousUserPass); }
            set { anonymousUserPass = value; }
        }

        /// <summary>
        /// Host header to bind to (only valid for non-SSL sites).
        /// </summary>
        /// <value>Host header to bind to (only valid for non-SSL sites).</value>
        public string HostName
        {
            get { return (hostName == null ? String.Empty : hostName); }
            set { hostName = value; }
        }

        /// <summary>
        /// Set the UserIsolationMode of the site - defaults 0
        /// </summary>
        public string UserIsolationMode
        {
            get { return userIsolationMode; }

            set { userIsolationMode = value; }
        }
    }
}